// pages/grid2_publish.js
const getAllEmergencies = require('../../utils/API').getAllEmergencies
const addEmergency = require('../../utils/API').addEmergency
const formatTime = require('../../utils/util').formatTime2
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isShowingPublishPage: false,
        emergencyList: [],
        publishData: {
            title: '',
            content: '',
            area: '',
            department: ''
        },
        initialPublishData: {
            title: '',
            content: '',
            area: '',
            department: ''
        }
    },

    onLoad() {
        this.refreshEmergencyList()
    },

    showPublishPage: function() {
        this.setData({
            isShowingPublishPage: true
        })
    },
    closePublishPage() {
        this.setData({
            isShowingPublishPage: false
        })
    },
    togglePublishPage() {
        this.setData({
            isShowingPublishPage: !this.data.isShowingPublishPage
        })
    },

    // 刷新页面数据
    refreshEmergencyList() {

        getAllEmergencies()
            .then(emergencies => {
                this.setData({
                    emergencyList: emergencies.map(v => Object.assign(v, {
                        formattedTime: formatTime(new Date(v.time))
                    }))
                })
            })
    },

    // 清空表单信息
    resetPublishForm() {
		let initialPublishData = this.data.initialPublishData
        this.setData(Object.keys(initialPublishData).reduce((obj, key) => {
            obj[`publishData.${key}`] = initialData[key]
            return obj
        }, {}))
    },


    confirmPublish() {
        addEmergency(this.data.publishData).then(() => {
            wx.showToast({
                title: '发布成功',
                icon: 'success'
            })
            this.refreshEmergencyList()
            this.closePublishPage()
            this.resetPublishForm()
        }, e => {

            wx.showToast({
                title: '发布失败',
                icon: 'none'
            })
        })
    },

	bindTitleInput(e){
		this.setData({
			'publishData.title': e.detail.detail.value
		})
	},
	bindContentInput(e) {
		this.setData({
			'publishData.content': e.detail.detail.value
		})
	},
	bindAreaInput(e) {
		this.setData({
			'publishData.area': e.detail.detail.value
		})
	},
	bindDepartmentInput(e) {
		this.setData({
			'publishData.department': e.detail.detail.value
		})
	},
})